var express = require('express');
var bodyParser = require('body-parser')
var request = require('request');
var router = express.Router();

var userData_control=require('../db_control/userData_control')
var app_id = ""
var app_secret = ""
var base_url = 'https://api.weixin.qq.com/sns/jscode2session'
var unionid;	
	
/* GET users listing. */
router.get('/', function(req, res, next) {
	var code = req.query.code

	var url = base_url + '?appid=' + app_id + '&secret=' + app_secret + '&js_code=' + code +"&grant_type=authorization_code"
	request(url, (error, response, body) => {
		var thebody=JSON.parse(body)
		console.log(thebody);
		unionid=thebody.openid
		res.end(body)
	})
 
}); 

router.post('/postUserInfo', function(req, res, next){
	console.log(req.body);
	var userdata={
		union_id:req.body.id,
		name:req.body.username,
		avatar:req.body.avatar
	}
	console.log(userdata);
	userData_control.add_data(userdata);
	res.send(unionid)
}) 

module.exports = router; 
